package com.zhidisoft.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhidisoft.common.Page;
import com.zhidisoft.system.dao.IFunctionDao;
import com.zhidisoft.system.dao.IRoleDao;
import com.zhidisoft.system.entity.Function;
import com.zhidisoft.system.entity.Role;
import com.zhidisoft.system.service.IRoleService;
import com.zhidisoft.system.vo.RoleVO;

@Service
public class RoleServiceImpl implements IRoleService {

	@Autowired
	private IRoleDao roleDao;
	
	@Autowired
	private IFunctionDao funcDao;

	@Override
	public String add(Role role) {
		return roleDao.save(role);
	}

	
	@Override
	public List<Role> findRolesByUserId(String userId) {
		
		return roleDao.findByUserId(userId);
	}

	@Override
	public List<Role> findAll() {
		
		return roleDao.find();
	}

	@Override
	public RoleVO findById(String id) {
		return RoleVO.fromRole( roleDao.get(id));
	}

	

	@Override
	public Page<RoleVO> findByPage(Long page, Long rows) {
		Long totalRows = roleDao.count();
		Page<RoleVO> pageBean = new Page<RoleVO>();
		pageBean.setTotalRows(totalRows);
		pageBean.setPageNumber(page);
		pageBean.setPageSize(rows);
		
		List<Role> list = roleDao.findByPage(pageBean.getPageNumber(), pageBean.getPageSize());
		List<RoleVO> result = new ArrayList<RoleVO>();
		for(Role role : list){
			result.add(RoleVO.fromRole(role));
		}
		pageBean.setResult(result);
		return pageBean;
	}


	@Override
	public boolean saveOrUpdate(Role role) {
		
		return roleDao.saveOrUpdate(role);
	}


	@Override
	public boolean updateFunctions(String roleId, String ids) {
		Role role = roleDao.get(roleId);
		//将该角色原有的权限清空
		role.getFunctions().clear();
		//将新的权限设置到role对象中
		String[] funcIds = ids.split(",");
		for(String funcId : funcIds){
			Function func = new Function();
			func.setId(funcId);
			
			role.getFunctions().add(func);
		}
		return true;
	}
	
	
}
